//
//  HomeTabViewController.m
//  IceBreaker
//
//  Created by 老焦 on 12-10-20.
//  Copyright (c) 2012年 NDS. All rights reserved.
//

#import "HomeTabViewController.h"
#import <QuartzCore/CALayer.h>
#import <QuartzCore/QuartzCore.h>
#import "PublicUtils.h"
#import "FeatureTableViewController.h"
#import "NearbyTableViewController.h"
#import "FilterViewController.h"
#import "EventDetailViewController.h"

@interface HomeTabViewController ()

@end

@implementation HomeTabViewController

@synthesize featureViewController;
@synthesize nearbyViewController;

@synthesize rightSeg;
@synthesize locationMgr;
@synthesize nowLocation;

/*
@synthesize listTable;
@synthesize listField;
@synthesize listArrary;
@synthesize showList;
@synthesize tableHeight;
@synthesize frameHeight;
*/

-(id) init {
    self = [super initWithNibName: nil bundle: nil];
    if (self) {
        // self.title = NSLocalizedStringFromTable(@"Tab home", @"Localizable", @"Home");
        UITabBarItem *contactTab = [self tabBarItem];
        UIImage *contactImage = [UIImage imageNamed: @"home.png"];
        contactTab.image = contactImage;
        contactTab.title = NSLocalizedStringFromTable(@"Tab home", @"Localizable", @"Home");
        self.tabBarItem = contactTab;
        
        UIImage *buttonImg = [UIImage imageNamed:@"filter.png"];
        CGRect buttonFrame = CGRectMake(0, 0, buttonImg.size.width, buttonImg.size.height);
        UIButton *filterButton = [UIButton buttonWithType: UIButtonTypeCustom];
        filterButton.layer.masksToBounds = YES;
        filterButton.layer.cornerRadius = 5.0;
        filterButton.frame = buttonFrame;
        [filterButton setBackgroundImage: buttonImg forState: UIControlStateNormal];
        [filterButton setTitleColor: [UIColor whiteColor]
                           forState: UIControlStateNormal];
        [filterButton addTarget: self
                         action: @selector(filterActivities:)
               forControlEvents: UIControlEventTouchUpInside];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView: filterButton];
        [self.navigationItem setLeftBarButtonItem: leftItem];
        [filterButton release];
        [leftItem release];
        /*
        UIView *titleView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 200, 20)];// allocate title view
        frameHeight = 20;
        tableHeight = 0;
        showList = NO;
        listTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, 200, 0)];
        listTable.delegate = self;
        listTable.dataSource = self;
        listTable.backgroundColor = [UIColor grayColor];
        listTable.separatorColor = [UIColor lightGrayColor];
        listTable.hidden = YES;
        [titleView addSubview: listTable];
        
        listField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
        listField.borderStyle=UITextBorderStyleRoundedRect;//设置文本框的边框风格
        [listField addTarget:self action:@selector(dropdown) forControlEvents:UIControlEventAllTouchEvents];
        [titleView addSubview:listField];
        [self.navigationItem.titleView addSubview: titleView];
        */

        // Create a segment control
        rightSeg = [[UISegmentedControl alloc] initWithFrame: CGRectMake(20, -5, 80, 30)];
        rightSeg.segmentedControlStyle = UISegmentedControlStyleBar;
        rightSeg.layer.masksToBounds = YES;
        rightSeg.layer.cornerRadius = 5.0;
        
        [rightSeg insertSegmentWithImage: [UIImage imageNamed:@"filter.png"]
                                 atIndex: 0
                                animated: YES];
        [rightSeg insertSegmentWithImage: [UIImage imageNamed:@"filter.png"]
                                 atIndex: 1
                                animated: YES];
        
        [rightSeg setSelectedSegmentIndex: 0];
        // The target of the segment control
        [rightSeg addTarget: self
                     action: @selector(changeSegment:)
           forControlEvents: UIControlEventValueChanged];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView: rightSeg];
        // Add the segment control to the view
        [self.navigationItem setRightBarButtonItem: rightItem];
        [rightSeg release];
        [rightItem release];
        
        //self.view.backgroundColor = [UIColor colorWithRed:10 green:148 blue:222 alpha:1];
    }
    return self;
}

- (id)initWithNibName: (NSString *)nibNameOrNil
               bundle: (NSBundle *)nibBundleOrNil {
    return [self init];
}

-(void) viewWillAppear:(BOOL)animated {
    [self.navigationController setToolbarHidden: YES];
    if (!locationMgr) {
        locationMgr = [[CLLocationManager alloc] init];
    }
    
    if ([CLLocationManager locationServicesEnabled]) {
        locationMgr.delegate = self;// set the delegate
        locationMgr.desiredAccuracy = kCLLocationAccuracyBest;// set the accuracy (best)
        locationMgr.distanceFilter = kCLDistanceFilterNone;
        [locationMgr startUpdatingLocation];// start to update the location
    } else {
        [PublicUtils alertMsgWithTitle: NSLocalizedStringFromTable(@"Alert tips", @"Localizable", @"Tips")
                               message: NSLocalizedStringFromTable(@"Location disabled", @"Localizable", @"Location service is disabled")
                     cancelButtonTitle: NSLocalizedStringFromTable(@"Confirm text", @"Localizable", @"OK") ];
    }
    
}

/*
-(void) viewDidAppear:(BOOL)animated {
    [self performSelector: @selector(automaticViewJump)
               withObject: nil
               afterDelay: 5];
}

-(void) automaticViewJump {
    EventDetailViewController *nxtView = [[EventDetailViewController alloc] initWithNibName: @"EventDetailViewController"
                                                                                     bundle: nil];
    nxtView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController: nxtView animated: YES];
    [nxtView release];
}
*/

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (self.featureViewController == nil) {
        FeatureTableViewController *featureView = [[FeatureTableViewController alloc] initWithNibName: @"FeatureTableViewController"
                                                                                               bundle: nil];
        self.featureViewController = featureView;
        // featureView.nowLocation = self.nowLocation;
        self.title = @"推荐";
        [featureView setParentViewController: self];
        [self.view insertSubview: featureView.view atIndex: 0];
        [featureView release];
    }
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark
#pragma mark - instance method
-(IBAction) changeSegment:(id)sender {
    UISegmentedControl *control = (UISegmentedControl *) sender;
    if (control == rightSeg) {
        [self changeTableView: control.selectedSegmentIndex];
    }
}

// switch the table view for segment
-(void) changeTableView:(int) segIndex {
    [UIView beginAnimations: @"View Flip"
                    context: nil];
    [UIView setAnimationDuration: 1.25f];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    if (segIndex == 0) {
        if (self.featureViewController == nil) {
            FeatureTableViewController *featureController = [[FeatureTableViewController alloc] initWithNibName: @"FeatureTableViewController"
                                                                                                         bundle: nil];
            self.featureViewController = featureController;
            // featureViewController.nowLocation = self.nowLocation;
            [featureController release];
        }
        [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft
                               forView: self.view
                                 cache: YES];
        [featureViewController setParentViewController: self];
        [nearbyViewController viewWillAppear: YES];
        [featureViewController viewWillDisappear: YES];
        
        [nearbyViewController.view removeFromSuperview];
        self.title = @"推荐";
        [self.view insertSubview: featureViewController.view  atIndex: 0];
        
        [featureViewController viewDidDisappear: YES];
        [nearbyViewController viewDidAppear: YES];
        
        self.nearbyViewController = nil;
    } else {
        if (self.nearbyViewController == nil) {
            NearbyTableViewController *nearbyController = [[NearbyTableViewController alloc] initWithNibName: @"NearbyTableViewController"
                                                                                                      bundle: nil];
            self.nearbyViewController = nearbyController;
            // featureViewController.nowLocation = self.nowLocation;
            [nearbyController release];
        }
        [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight
                               forView: self.view
                                 cache: YES];
        [nearbyViewController setParentViewController: self];
        [featureViewController viewWillAppear: YES];
        [nearbyViewController viewWillDisappear: YES];
        
        [featureViewController.view removeFromSuperview];
        self.title = @"周边";
        [self.view insertSubview: nearbyViewController.view atIndex: 0];
        [nearbyViewController viewDidDisappear: YES];
        [featureViewController viewDidAppear: YES];
        
        self.featureViewController = nil;
    }
    
}

//
-(IBAction) filterActivities:(id)sender {
    FilterViewController *filterView = [[FilterViewController alloc] initWithNibName: @"FilterViewController"
                                                                              bundle: nil];
    
    CATransition *transition = [CATransition animation];
    transition.duration = 1;
    transition.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromTop;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation: transition
                                                forKey: nil];
    
    [self.navigationController pushViewController: filterView animated:YES];
    [filterView release];
}

#pragma mark
#pragma mark - methods for CLLocationManagerDelegate
#pragma mark - CLLocationManagerDelegate
-(void) locationManager: (CLLocationManager *)manager
    didUpdateToLocation: (CLLocation *)newLocation
           fromLocation: (CLLocation *)oldLocation {
    NSLog(@"New location is %@", [newLocation description]);
    nowLocation = newLocation;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation: newLocation
                   completionHandler: ^(NSArray *placemarks, NSError *error) {
                       for(CLPlacemark *placemark in placemarks) {
                           NSString *location = [NSString stringWithFormat:@"%@%@",
                                                 [[placemark.addressDictionary objectForKey:@"City"] substringToIndex:3],
                                                 [placemark.addressDictionary objectForKey:@"SubLocality"]];
                           NSLog(@"您的当前位置为:%@", location);
                       }
                   }];
    
    [self foundLocation: newLocation];
}

-(void) locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {
    NSString *errorMsg = @"NULL";
    if ([error code] == kCLErrorDenied) {
        errorMsg = NSLocalizedStringFromTable(@"Access denied", @"Localizable", @"Access denied");
    } else if ([error code] == kCLErrorLocationUnknown) {
        errorMsg = NSLocalizedStringFromTable(@"Locate Failure", @"Localizable", @"Failed to get the location");
    }
    [PublicUtils alertMsgWithTitle: NSLocalizedStringFromTable(@"Alert tips", @"Localizable", @"Tips")
                           message: errorMsg
                 cancelButtonTitle: NSLocalizedStringFromTable(@"Confirm text", @"Localizable", @"OK")];
}

-(void) findLocation {
    [locationMgr startUpdatingLocation];
}

-(void) foundLocation: (CLLocation *) location {
    NSString *latitude = [NSString stringWithFormat: @"%f", location.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat: @"%f", location.coordinate.longitude];
    NSString *altitude = [NSString stringWithFormat: @"%f", location.altitude];
    
    NSLog(@"当前位置三维信息，经度：%@，纬度：%@，海拔：%@。", latitude, longitude, altitude);
    [locationMgr stopUpdatingLocation];
}

@end
